package com.lanou3g.exam.view;

import com.lanou3g.exam.controller.LoginController;
import com.lanou3g.exam.pojo.User;
import com.lanou3g.exam.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login.action")
public class LoginServlet extends HttpServlet {
    private LoginController loginController = new LoginController();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String pwd = MD5Util.MD5WithSalt(request.getParameter("password"));

//        String verify = request.getParameter("verify");
//        String text = (String) request.getSession().getAttribute("verify");
//        if (text == null || !text.equalsIgnoreCase(verify)) {
//            filedMsg(request, response, "验证码错误");
//            return;
//        }
        User user = loginController.login(username, pwd);

        if (user == null) {
            filedMsg(request, response, "用户名/密码错误,点击返回登录页面");

        } else {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("index.jsp");
        }

    }

    private void filedMsg(HttpServletRequest request,
                          HttpServletResponse response,
                          String msg) throws ServletException, IOException {
        String path = "/login.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        response.setStatus(302);
        response.setHeader("refresh", "5,URL=/login.jsp");
        request.getRequestDispatcher("msg.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
